package tech.yangzhijie.basic.knowledge.other;

public class ProducerAndConsumerTest {

    public static void main(String[] args) {
        Resources resources = new Resources();

        Producer producer = new Producer(resources);
        Consumer consumer = new Consumer(resources);

        new Thread(producer,"生产者A").start();
        new Thread(consumer,"消费者A").start();

        new Thread(producer,"生产者B").start();
        new Thread(consumer,"消费者B").start();

        new Thread(producer,"生产者C").start();
        new Thread(consumer,"消费者C").start();
    }

}

class Resources{

    private int num = 0;

    /**
     * 资源增加
     */
    public synchronized void add(){
        while (num >= 10){
            System.out.println("资源已满！");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + " : " + ++num);
        this.notifyAll();
    }

    /**
     * 资源减少
     */
    public synchronized void reduce(){
        while (num <= 0){
            System.out.println("缺货中……");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + " : " + --num);
        this.notifyAll();

    }
}

class Producer implements Runnable{

    private Resources resources;

    public Producer(Resources resources) {
        this.resources = resources;
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++){
            resources.add();
        }
    }
}

class Consumer implements Runnable{

    private Resources resources;

    public Consumer(Resources resources) {
        this.resources = resources;
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++){
            resources.reduce();
        }
    }
}
